<?php
/**
 * @author xialei <xialeistudio@gmail.com>
 */

namespace app\components;


use app\exception\ErrorCode;
use yii\base\Exception;
use yii\db\ActiveRecord;

class Service
{
    protected static $_instance = array();

    /**
     * 实例化
     * @param string $className
     * @return self
     */
    public static function instance($className = __CLASS__)
    {
        if (empty(self::$_instance[$className])) {
            self::$_instance[$className] = new $className();
        }
        return self::$_instance[$className];
    }

    /**
     * 获取模型错误
     * @param ActiveRecord $model
     * @return mixed
     */
    protected function getError($model)
    {
        $error = $model->firstErrors;
        if (is_array($error)) {
            return array_shift($error);
        }
        return null;
    }

    /**
     * @author xialei <xialeistudio@gmail.com>
     * @param $url
     * @param array $params
     * @return mixed
     * @throws Exception
     */
    public function get($url, $params = [])
    {
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            throw new Exception('url地址不合法', ErrorCode::URL_INVALID);
        }
        $url .= strpos($url, '?') === false ? '?' . http_build_query($params) : '&' . http_build_query($params);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}
